/*
 * Copyright 2007 Rob Nielsen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.proxymatic.apps.data.calculators;

import com.googlecode.proxymatic.apps.data.FieldNameCalculator;
import com.googlecode.proxymatic.apps.data.Key;
import com.googlecode.proxymatic.core.SimpleObject;

import java.lang.reflect.Method;

public class BasicFieldNameCalculator extends SimpleObject implements FieldNameCalculator {
    private static final String GET = "get";
    private static final String IS = "is";
    private static final String SET = "set";
    private static final String[] ACCESSORS = {GET, SET, IS};

    protected String getBasicFieldName(Method method) {
        String name = method.getName();
        int start = getStartOfName(name);
        return name.substring(start, start + 1).toLowerCase() + name.substring(start + 1);
    }

    public boolean isGetter(Method method) {
        String name = method.getName();
        return (name.startsWith(GET) || name.startsWith(IS)) &&
                method.getParameterTypes().length == 0 &&
                !method.getReturnType().equals(void.class);
    }

    public boolean isSetter(Method method) {
        return method.getName().startsWith(SET) &&
                method.getParameterTypes().length == 1 &&
                method.getReturnType().equals(void.class);
    }

    public String getBackingMapKeyName(Method method) {
        Key annotation = method.getAnnotation(Key.class);
        if (annotation != null) {
            return annotation.value();
        }
        return getBasicFieldName(method);
    }

    private int getStartOfName(String name) {
        for (int i = 0; i < ACCESSORS.length; i++) {
            if (name.startsWith(ACCESSORS[i])) {
                return ACCESSORS[i].length();
            }
        }
        throw new IllegalArgumentException("Can find field name for method " + name);
    }
}
